<?php

require_once dirname(__FILE__).'/../lib/pertinenciaGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/pertinenciaGeneratorHelper.class.php';

/**
 * pertinencia actions.
 *
 * @package    sistema_estadisticas
 * @subpackage pertinencia
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class pertinenciaActions extends autoPertinenciaActions
{

	public function executeShow(sfWebRequest $request)
	{
		if (!PertinenciaTable::getInstance()->hasAccess($request->getParameter('id'), $this->getUser()->getUserId()))
			$this->forward('login', 'secure');

		$this->pertinencia = PertinenciaTable::getInstance()->fetchOne($request->getParameter('id'));

		$this->tesis_id = 0;
		if ($this->pertinencia->getTesis() !== null)
			$this->tesis_id = $this->pertinencia->getTesis()->getId();
	}

	public function executeBuscar(sfWebRequest $request)
	{
		if ($request->isXmlHttpRequest())
		{
			$tema = $request->getParameter('tema');
			$docente_id = $request->getParameter('docente_id');
			
			return $this->renderText(json_encode(PertinenciaTable::getInstance()->buscar($tema, $docente_id)));
		}
	}

	public function executeTesis(sfWebRequest $request)
	{
		if (!PertinenciaTable::getInstance()->hasAccess($request->getParameter('id'), $this->getUser()->getUserId()))
			$this->forward('login', 'secure');

		$pertinencia_id = $request->getParameter('id');
		$this->forward404Unless($pertinencia_id);
		$this->tesis = new Tesis();
		$this->tesis->setPertinenciaId($pertinencia_id);
		$this->form = new TesisForm($this->tesis);

		if ($request->isMethod('post'))
			$this->processFormTesis($request, $this->form);

		$this->setTemplate('createTesis');
	}
	
	private function processFormTesis(sfWebRequest $request, $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{
			$notice = 'El proyecto se ha creado correctamente.';

			try
			{
				$this->tesis = $form->save();
			}
			catch (Doctrine_Validator_Exception $e)
			{
				$errorStack = $form->getObject()->getErrorStack();

				$message = get_class($this->form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
				foreach ($errorStack as $field => $errors)
				{
					$message .= "$field (" . implode(", ", $errors) . "), ";
				}
				$message = trim($message, ', ');

				$this->getUser()->setFlash('error', $message);
				return sfView::SUCCESS;
			}

			$this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $this->tesis)));

			$this->getUser()->setFlash('notice', $notice);
			$this->redirect('@tesis_show?id=' . $this->tesis->id);
		}
		else
		{
			$this->getUser()->setFlash('error', 'El proyecto no se ha guardado porque se ha producido algún error.', false);
		}
	}

	public function executeCompare(sfWebRequest $request)
	{
		parent::executeCompare($request);

		$table = PertinenciaEstudianteTable::getInstance();

		$this->current_relations = array();
		$this->previous_relations = array();

		$this->current_relations['Estudiante'] = $table->getCurrentVersion($this->current->id);
		$this->previous_relations['Estudiante'] = $table->getVersion($this->previous->id, $this->previous->version);
	}

	public function executeDeleteVersion(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$id = $request->getParameter('id');
		$version = $request->getParameter('version');

		$table = PertinenciaTable::getInstance();

		try
		{
			$table->deleteVersions($id, $version);
			$this->getUser()->setFlash('notice','La versión seleccionada se ha borrado correctamente.');
		}
		catch (Exception $e)
		{
			$this->getUser()->setFlash('error', 'Se ha producido un error al borrar la versión seleccionada.');
		}

		$this->redirect('@' . $this->helper->getUrlForAction('historic?id=') . $id);
	}

	public function executeBatchDeleteVersion(sfWebRequest $request)
	{
		$request->checkCSRFProtection();

		$versions = $request->getParameter('versions');
		$id = $request->getParameter('id');

		$table = PertinenciaTable::getInstance();

		try
		{
			$table->deleteVersions($id, $versions);
			$this->getUser()->setFlash('notice', 'Las versiones seleccionadas se han eliminado con correctamente.');
		}
		catch (Exception $e)
		{
			$this->getUser()->setFlash('error', 'Se ha producido un error al borrar las versiones seleccionadas.');
			throw $e;
		}

		$this->redirect('@' . $this->helper->getUrlForAction('historic?id=') . $id);
	}

}
